<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :width="'70%'" >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12" >
          <el-form-item label="第几周" prop="weekDate">
            <el-date-picker
              v-model="formData.weekDate"
              type="week"
              format="[第] ww [周]"
              placeholder="请选择周"
              value-format="x"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="周主题" prop="topicName">
            <el-input v-model="formData.topicName" placeholder="请输入周计划主题名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="开始时间 " prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              value-format="x"
              placeholder="选择开始时间 "
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间 " prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            value-format="x"
            placeholder="选择结束时间"
          />
          </el-form-item>
        </el-col>
      </el-row> -->
    
      <el-divider content-position="left" class="blue-divider">基础信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工作重点" prop="workFocus">
            <el-input v-model="formData.workFocus" type="textarea" placeholder="请输入工作重点" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="家长配合" prop="parentCoop">
            <el-input v-model="formData.parentCoop" type="textarea" placeholder="请输入家长配合" />
          </el-form-item>
        </el-col> 
      </el-row>
      
      <el-form-item label="快乐生活" prop="happyLife">
        <el-input v-model="formData.happyLife" type="textarea" placeholder="请输入快乐生活" />
      </el-form-item>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="周计划每日内容" name="weeklyPlanDaily">
        <WeeklyPlanDailyForm ref="weeklyPlanDailyFormRef" :plan-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { WeeklyPlanApi, WeeklyPlanVO } from '@/api/school/weeklyplan'
import WeeklyPlanDailyForm from './components/WeeklyPlanDailyForm.vue'
import dayjs from 'dayjs';          
import isoWeek from 'dayjs/plugin/isoWeek';
import isoWeeksInYear from 'dayjs/plugin/isoWeeksInYear';
dayjs.extend(isoWeek);
dayjs.extend(isoWeeksInYear);

/** 周计划 表单 */
defineOptions({ name: 'WeeklyPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  classId: 0,
  topicName: undefined,
  weekDate: undefined,
  weekNumber: undefined,
  startDate: undefined,
  endDate: undefined,
  workFocus: undefined,
  parentCoop: undefined,
  happyLife: undefined,
  sort: undefined,
  status: undefined,
})
const formRules = reactive({
  topicName: [{ required: true, message: '主题活动名称不能为空', trigger: 'blur' }],
  weekDate: [{ required: true, message: '第几周不能为空', trigger: 'blur' }],
  startDate: [{ required: true, message: '开始时间 不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('weeklyPlanDaily')
const weeklyPlanDailyFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, classId:number, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  //赋值classId
  formData.value.classId = classId

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await WeeklyPlanApi.getWeeklyPlan(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await weeklyPlanDailyFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'weeklyPlanDaily'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    console.log('formData--',formData.value.weekDate)
    
    const data = formData.value as unknown as WeeklyPlanVO

    console.log('data week--',data.weekDate)
    //处理周日期信息
    const weekInfo = getWeekInfo(data.weekDate)
    data.weekYear = weekInfo.year
    data.weekNumber = weekInfo.weekNumber
    // 检查 weekInfo.range 是否为 null 或 undefined，如果是则将 startDate 设置为 null，否则创建 Date 对象
    data.startDate = weekInfo.range ? weekInfo.range.start : null;
    data.endDate = weekInfo.range ? weekInfo.range.end : null;

    // 拼接子表的数据
    data.weeklyPlanDailys = weeklyPlanDailyFormRef.value.getData()
    if (formType.value === 'create') {
    console.log('data week--create--',data.weekDate)
      await WeeklyPlanApi.createWeeklyPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await WeeklyPlanApi.updateWeeklyPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    classId: 0,
    topicName: undefined,
    weekDate: undefined,
    weekNumber: undefined,
    startDate: undefined,
    endDate: undefined,
    workFocus: undefined,
    parentCoop: undefined,
    happyLife: undefined,
    sort: undefined,
    status: undefined,
  }
  formRef.value?.resetFields()
}

/** 处理周日期信息 */
function getWeekInfo(date) {
  console.log(date,'选择的周日期---');
  
  if (!date) return { year: null, weekNumber: null, range: null };

  const d = dayjs(date);
  const weekNumber = d.isoWeek();     // 获取 ISO 周序号
  const year = d.isoWeekYear();       // 获取 ISO 周对应的年份

  const start = d.startOf('isoWeek').valueOf();
  const end = d.endOf('isoWeek').valueOf();
  //const end = d.endOf('isoWeek').format('YYYY-MM-DD');

  return {
    year,
    weekNumber,
    range: { start, end }
  };
}


</script>

<style scoped>
:deep(.blue-divider .el-divider__text) {
  color: rgb(64, 158, 255);
}
</style>